﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using System.Security.Cryptography;
using System.IO;

namespace TestClient
{
    public partial class ClientForm : Form
    {

        public ClientForm()
        {
            InitializeComponent();
        }
        private void ClientForm_Load(object sender, EventArgs e)
        {
            showMsg("程序启动");

            txtbIP.Text = "127.0.0.1";
            txtbPort.Text = "5200";
            //TODO:做一些变量初始化工作
        }
        private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //TODO:退出前清理数据
            showMsg("程序关闭中……");
        }


        /// <summary>
        /// 显示消息提示
        /// </summary>
        /// <param name="msg">消息内容</param>
        private void showMsg(string msg)
        {
            if (this.lbxMsg.IsDisposed)
                return;
            
            if (lbxMsg.InvokeRequired)
            {
                var de = new Action<string>(showMsg);//Action为.net为我们定义好的泛型委托，他可以有0个到16个输入参数，但无返回值
                lbxMsg.Invoke(de, msg);
            }
            else
            {
                if (lbxMsg.Items.Count > 200)
                {
                    lbxMsg.Items.RemoveAt(0);
                }
                lbxMsg.Items.Add(msg);
                lbxMsg.TopIndex = lbxMsg.Items.Count - (int)(lbxMsg.Height / lbxMsg.ItemHeight);
            }
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            try
            {
                showMsg("连接服务器……");
                string ip = txtbIP.Text.Trim();
                ushort port = ushort.Parse(txtbPort.Text.Trim());
                //TODO:连接服务器
            }
            catch (Exception exp)
            {
                showMsg(exp.Message);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            showMsg("断开服务器连接");
            //TODO:连接服务器
        }

        ///<summary>字符串DES加密函数</summary>  
        ///<param name="str">被加密字符串 </param>  
        ///<param name="key">密钥 8字符</param>   
        ///<returns>加密后字符串</returns>     
        public static string Encode(string str, string key)  
        {  
            try  
            {  
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                provider.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                provider.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(str);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();

                StringBuilder builder = new StringBuilder();
                foreach (byte num in stream.ToArray())  
                {  
                    builder.AppendFormat("{0:X2}", num);
                }  
                stream.Close();
                return builder.ToString();
            }  
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
                return "";
            }  
        }  
        ///<summary>字符串DES解密函数</summary>  
        ///<param name="str">被解密字符串 </param>  
        ///<param name="key">密钥 8字符</param>   
        ///<returns>解密后字符串</returns>     
        public static string Decode(string str, string key)  
        {  
            try  
            {  
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                provider.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                provider.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] buffer = new byte[str.Length / 2];
                for (int i = 0; i < (str.Length / 2); i++)  
                {  
                    int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
                    buffer[i] = (byte)num2;
                }  
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                stream.Close();
                return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
                return "";
            }
        }  
     

        private void btnSend_Click(object sender, EventArgs e)
        {
            showMsg("发送数据");
            //string en=Encode("123abc", "lding016");
            //string de = Decode(en, "lding016");

            //return;
            string sendContent = txtMsg.Text;
            if (sendContent.Length < 1)
            {
                return;
            }
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(sendContent);
                //TODO:发送数据
            }
            catch (Exception exp)
            {
                showMsg(string.Format("发送失败：{0}", exp.Message));
            }
        }

        //TODO:通过监听SOCKET事件接收数据

        /*
        private string getJysbm()
        {
            string id = "11111000000000579";
            DataTable dt = SQLHelper.select("DTJBXX01", "xsp", "xt", "dtzcdm,dtjysbm".Split(','), "".Split(','), new object[] { "xsp", "(", "dtid", "等于", id, ")", "或者" });
            return dt.Rows[0]["dtjysbm"].ToString();
        }
         */
    }
}
